//
//  CreateMyAccount_First.m
//  Bespoke
//
//  Created by Cheng on 12/10/8.
//
//

#import "CreateMyAccount_First.h"
#import "GDataXMLNode.h"
#import "AccountParser.h"
#import <Accounts/Accounts.h>
#import "RequestAPIFunction.h"
#import "AccountInfo.h"
#import "AppDelegate.h"

#define NEWUSER_API @"http://54.235.166.43/BeSpokeAPI/newUser.php"
#define USERINFO_API @"http://54.235.166.43/BeSpokeAPI/userInfo.php"

@implementation CreateMyAccount_First
@synthesize Tf_FullName, Tf_Email, Tf_Password, Array_AccountInfo, BK_En_object;
@synthesize delegate;

-(IBAction)ContinuePressed:(id)sender {
    
    [NSThread detachNewThreadSelector:@selector(threadStartAnimating:) toTarget:self withObject:nil];
    
    if (([Tf_FullName.text isEqualToString:@""])||(Tf_FullName.text==nil)) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Full Name is null." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    else if (([Tf_Email.text isEqualToString:@""])||(Tf_Email.text==nil)) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Email is null." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    else if (([Tf_Password.text isEqualToString:@""])||(Tf_Password.text==nil)) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Password is null." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    else if ([Tf_Email.text rangeOfString:@"@"].location == NSNotFound) {//Check username is or not Email.
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"The Email you entered is incorrect." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    
    //User XML requst API.
    NSData *responseData =
    [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<AccountInfo UserName=\"%@\" Password=\"%@\" Name=\"%@\" Level=\"iPadUser\" Organization=\"Bespoke\" />",
                               Tf_Email.text,
                               Tf_Password.text,
                               Tf_FullName.text]
                              urlString:NEWUSER_API];
    
    //No Network Connection or time out.
    if (responseData == nil)
        return;
    
    NSError *error;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:responseData options:0 error:&error];
    
    
    //Check to upload is success.
    if ([[doc nodesForXPath:@"//Registered" error:&error] count]!=0) {//Account Registered
        
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Account Registered." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        
    }
    else if ([[doc nodesForXPath:@"//Success" error:&error] count]!=0) {
        
        
        [self RequestAPI:Tf_Email.text SetPassWord:Tf_Password.text SetFullName:Tf_FullName.text SetSource:@"TPN"];
        
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Registration has been successful." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView setTag:101];
        [AlertView show];
    }
}

#pragma mark - Facebook

-(IBAction)SignInFacebookPressed:(id)sender {
    AppDelegate *BespokeAppDelegate = [[UIApplication sharedApplication] delegate];
    
    if(!BespokeAppDelegate.session.isOpen) {
        NSArray *permissions = [NSArray arrayWithObjects:
                                @"user_photos",
                                @"user_videos",
                                @"publish_stream",
                                @"offline_access",
                                @"user_checkins",
                                @"friends_checkins",
                                @"email",
                                @"user_location",
                                @"read_stream", nil];
        
        FBSession *pSession = [[FBSession alloc] initWithAppID:@"384457058286773" permissions:permissions urlSchemeSuffix:nil tokenCacheStrategy:nil];
        
        BespokeAppDelegate.session = pSession;
        
        
        [BespokeAppDelegate.session openWithCompletionHandler:^(FBSession *session,
                                                                FBSessionState status,
                                                                NSError *error) {
            // and here we make sure to update our UX according to the new session state
            
            [self updateFBAPI];
        }];
    }

}

-(void)updateFBAPI
{
    [NSThread detachNewThreadSelector:@selector(threadStartAnimating:) toTarget:self withObject:nil];
    
    AppDelegate *beSpokeAppDelegate = [[UIApplication sharedApplication] delegate];
    
    FBRequest *me = [[FBRequest alloc] initWithSession:beSpokeAppDelegate.session graphPath:@"me"];
    
    [me startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error)
     {
         NSString *result = [NSString stringWithFormat:@"https://graph.facebook.com/%@/home?access_token=%@", user.id, beSpokeAppDelegate.session.accessToken];
         
         if(beSpokeAppDelegate.session.isOpen)
         {
             NSLog(@"Facebook API Link = %@",result ) ;
             
             [self RequestAPI:[user objectForKey:@"email"] SetPassWord:@"" SetFullName:[NSString stringWithFormat:@"%@ %@",user.first_name,user.last_name] SetSource:@"Facebook"];
             
             [BK_En_object setAccountInfoFaceBookID:user.id setFaceBookTotken:beSpokeAppDelegate.session.accessToken];
             
             UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Login has been sucessful." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
             [AlertView setTag:101];
             [AlertView show];
         }
         else {
             UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Facebook Called Failed." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
             [AlertView show];
         }
     }];
}

#pragma mark - Twitter

-(IBAction)SignInTwitterPressed:(id)sender {
    ACAccountStore *accountStore = [[ACAccountStore alloc] init];
    ACAccountType *twitterType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    
    [accountStore requestAccessToAccountsWithType:twitterType withCompletionHandler:^(BOOL granted, NSError *error) {
        if (!granted) {
        }
        else {
            NSArray *accounts = [accountStore accountsWithAccountType:twitterType];
            ACAccount *ACA_Array = [accounts objectAtIndex:0];
            if ([ACA_Array valueForKey:@"username"]==nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please set up your Twitter account in your Personal settings?" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                    [AlertView show];
                });
                return;
            }
            
            if ([[ACA_Array valueForKey:@"username"] rangeOfString:@"@"].location == NSNotFound) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.delegate EditTwitterEmailPressed:[ACA_Array valueForKey:@"username"] SetFullName:[[ACA_Array valueForKey:@"properties"] valueForKey:@"fullName"]];
                });
                return;
            }
            
            
            [NSThread detachNewThreadSelector:@selector(threadStartAnimating:) toTarget:self withObject:nil];
            
            [self RequestAPI:[ACA_Array valueForKey:@"username"] SetPassWord:@"" SetFullName:[[ACA_Array valueForKey:@"properties"] valueForKey:@"fullName"] SetSource:@"Twitter"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Login has been sucessful." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                [AlertView setTag:101];
                [AlertView show];
            });
        }
    }];
}

#pragma mark - RequestAPI

-(void)RequestAPI:(NSString *)UserName SetPassWord:(NSString *)PassWord SetFullName:(NSString *)FullName SetSource:(NSString *)AccountSource {
    
    NSData *responseData = 
    [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<Authentication UserName=\"%@\" Password=\"%@\" Name=\"%@\" Source =\"%@\" Plaintext=\"True\" />",
                               UserName, PassWord, FullName, AccountSource]
                              urlString:USERINFO_API];
    
    //No Network Connection or time out.
    if (responseData == nil)
        return;
    
    Array_AccountInfo = [AccountParser loadAccountInfo:responseData];
    
    if ([Array_AccountInfo count]!=0) {
        
        [BK_En_object setAuthenticationUserName:UserName Password:PassWord];
        [BK_En_object setAccountInfoFullName:((AccountInfo *)[Array_AccountInfo objectAtIndex:0]).NS_AccountFullName setPartner:nil];
    }
}

#pragma mark - UIAlertViewDelegate

- (void)willPresentAlertView:(UIAlertView *)alertView {
    [[self viewWithTag:103] removeFromSuperview];
    [[self viewWithTag:104] removeFromSuperview];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag==101) {
        [self.delegate SignUpSuccess_First];
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if(textField == Tf_FullName)
        [Tf_Email becomeFirstResponder];
    else if(textField == Tf_Email)
        [Tf_Password becomeFirstResponder];
    else if(textField == Tf_Password)
        [self ContinuePressed:textField];
    return YES;
}

#pragma mark - Loading

-(void)threadStartAnimating:(id)data {
    
    UIView *Vw_Loading = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1024, 780)];
    [Vw_Loading setTag:103];
    [Vw_Loading setBackgroundColor:[UIColor blackColor]];
    [Vw_Loading setAlpha:0.5];
    
    UIActivityIndicatorView *ActivityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    ActivityView.hidesWhenStopped = YES;
    ActivityView.hidden = NO;
    ActivityView.center = CGPointMake(1024/2, 768/2);
    [ActivityView setTag:104];
    
    [self addSubview:Vw_Loading];
    [self addSubview:ActivityView];
    
    [ActivityView startAnimating];
}

@end
